﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Yahoo.Yui.Compressor;

namespace Mcmurphy.Common
{
    public class JsCombiner
    {
        /// <summary>
        /// 拼接js文件内容
        /// </summary>
        /// <param name="jsPaths"></param>
        /// <param name="serverPath"></param>
        /// <param name="isCompress"></param>
        /// <returns></returns>
        public static string CombineJs(string[] jsPaths, string serverPath, bool isCompress)
        {
            var jsBuilder = new StringBuilder();
            foreach (string path in jsPaths)
            {
                if (File.Exists(path))
                {
                    var sourceFileContent = AutoDetectEncodingFileReader.ReadFileContent(path, Encoding.Default);
                    if (string.IsNullOrEmpty(sourceFileContent) == false)
                    {
                        if (isCompress)
                        {
                            var compressor = new JavaScriptCompressor();
                            //ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8, Default (default).
                            compressor.Encoding = Encoding.UTF8;
                            //True (default) | False.  True => Obfuscate function and variable names
                            compressor.ObfuscateJavascript = true;
                            //True | False (default).  True => compress any functions that contain 'eval'. Default is False, which means a function that contains
                            compressor.IgnoreEval = false;
                            //True | False (default).
                            compressor.DisableOptimizations = false;
                            //True | False (default).  True => preserve redundant semicolons (e.g. after a '}'
                            compressor.PreserveAllSemicolons = false;
                            //The position where a line feed is appened when the next semicolon is reached. 
                            compressor.LineBreakPosition = -1;
                            sourceFileContent = compressor.Compress(sourceFileContent);
                        }
                        jsBuilder.Append(sourceFileContent);
                    }
                }
                else
                {
                    jsBuilder.Append(string.Format("/*未找到文件{0}*/", path.Replace(serverPath, "")));
                }
            }
            return jsBuilder.ToString();
        }


    }
}
